package mylab.starters.mq.config.rabbitmq;

import com.rabbitmq.client.ConnectionFactory;
import lombok.RequiredArgsConstructor;
import mylab.starters.mq.config.MqAutoConfiguration;
import mylab.starters.mq.config.MqPropperties;
import mylab.starters.mq.impl.rabbitmq.RabbitTemplate;
import mylab.utils.common.NetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@AutoConfigureAfter(MqAutoConfiguration.class)
@ConditionalOnProperty(value = RabbitMqAutoConfiguration.PREFIX, havingValue = "true")
public class RabbitMqAutoConfiguration {

    static final public String PREFIX = MqPropperties.PREFIX + ".rabbitmq.enabled";

    final private MqPropperties mqPropperties;

    @Bean
    public ConnectionFactory factory() {
        MqPropperties.RabbitMqProperties rabbit = mqPropperties.getRabbitmq();
        NetUtil.Broker broker = NetUtil.getFirstBroker(rabbit.getBrokers());

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(broker.getHost());
        factory.setPort(broker.getPort());
        factory.setUsername(rabbit.getUser());
        factory.setPassword(rabbit.getPassword());
        factory.setVirtualHost(rabbit.getVirtualHost());
        return factory;
    }


    @Bean
    @ConditionalOnMissingBean
    public RabbitTemplate template() {
        return new RabbitTemplate(this.mqPropperties.getRabbitmq());
    }
}
